#					-*-	coding: utf-8 -*-

import re
import os
import bz2

repos = (
		("http://ftp.ru.debian.org/debian/", "lenny", "main non-free contrib"),
		("http://security.debian.org/", "lenny/updates", "main non-free contrib"),
		("http://www.backports.org/debian/", "lenny-backports", "main contrib non-free"),
		)
arch = "i386"
fetch_command = "wget -c -q"
packages_file = "Packages.bz2"

def make_pkg_list():
	"""
	***	Возвращает список из пар [имя_пакета, версия_пакета]
	"""
	f = open('upgrade.log')
	r = re.compile(r"^Inst\ (?P<pname>[\w|\d|\-|\.|\+]+)\ .*?\ \((\d:)?(?P<pver>.+?)\ Debian")
	list = []
	for line in f:
		m = r.search(line)
		if not m: continue 
		pname = m.group('pname')
		pver = m.group('pver')
		list.append([pname, pver])
	f.close()
	return list

def unpack(file, new_name):
	out_f = open(new_name, "w")
	f = bz2.BZ2File(file, "r")
	for l in f:
		out_f.write(l)
	f.close()
	out_f.close()
	os.remove(file)

def find_pkg_info(pkg_name, info_file_l):
	"""
	*** pkg_name - имя пакета
	*** info_file_l - список информационных файлов для поиска
	*** Возвращает пару [имя_файла, путь_к_deb_файлу_в_репозитории]
	"""
	r_pkg = re.compile(r"%s" % pkg_name)
	r_file = re.compile(r"Filename:\ (?P<pname>.*)$")
	for info_file in info_file_l:
		f = open(info_file, "r")
		for line in f:
			m = r_file.match(line)
			if m and r_pkg.search(line):
#				print("Found %s, %s" % (pkg_name, m.group("pname")) )
				return (m.group("pname"), info_file)
		f.close()
	return (pkg_name, "")

def get_pkg_info(rep_l, pkg_l):
	"""
	*** rep_l - Список репозиториев
	*** pkg_l - Список имен пакетов
	*** Возвращает список пар [имя_пакета, путь_репозитории]
	"""
	pkg_info = []
	info_file_names = []
	for (url, dist, subdirs) in rep_l:
		for s in subdirs.split(" "):
			url_full = "/".join([url[:-1], "dists", dist, s]) + "/binary-" + arch + "/"
			unpack_file_name = url_full.replace("/", "_").replace("http:", "")
			if not os.path.exists(unpack_file_name):
				if os.system("%s %s%s" % (fetch_command, url_full, packages_file)):
					print("Ошибка при получении %s !" % (url_full + packages_file))
				else:
					print("Получен файл %s." % (url_full + packages_file))
					unpack(packages_file, unpack_file_name)
			else:	
				print("Файл %s уже существует!" % unpack_file_name)
			info_file_names.append(unpack_file_name)
	for pkg in pkg_l:
		find_res = find_pkg_info(pkg, info_file_names)
		if not find_res[1]:
			print("Package %s not found." % pkg)
			continue
		fake_url = "http:" + find_res[1].replace("_", "/")
		for l in [x[0] for x in repos]:
			if l in fake_url:
				site_url = l
		pkg_info.append((pkg, site_url + find_res[0]))
	return pkg_info
				

def get_deb(info):
	"""
	*** info - Пара [имя_пакета, URL для закачки]
	*** Возвращает пару списков с именнами пакетов [скаченные, нескаченные]
	"""
	success = []
	fail = []
	for (p, l) in info:
		if os.system("%s %s" % (fetch_command, l)):
			fail.append(p)
		else:
			success.append(p)
	return (success, fail)

pkg_list = [x[0] for x in  make_pkg_list()]
pkg_info = get_pkg_info(repos, pkg_list)
res = get_deb(pkg_info)
print("Успешно скачанно %s пакетов." % len(res[0]))
if res[1]:
	print("Не удалось скачать %s пакетов:" % len(res[1]))
	for s in res[1]:
		print("\t%s" % s)

#Inst gij-4.2 [4.2.1-5] (1:4.2.4-4 Debian:5.0.4/stable) [google-chrome-beta ]	
